/**     
 * @Title: NettyServletRegistration.java   
 * @Package me.springboot.netty.servlet   
 * @Description: TODO
 * @author weiwei 
 * @date 2017年8月25日 下午2:54:06   
 * @version V1.0     
 */
package me.springboot.netty.servlet;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import javax.servlet.MultipartConfigElement;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletSecurityElement;

import me.springboot.netty.context.NettyEmbeddedContext;

/**
 * @ClassName: NettyServletRegistration
 * @Description: TODO
 * @author weiwei
 * @date 2017年8月25日 下午2:54:06
 * 
 */
public class NettyServletRegistration extends AbstractNettyRegistration implements ServletRegistration.Dynamic {
	
	private volatile boolean initialised;
	
	private Servlet servlet;

	public NettyServletRegistration(NettyEmbeddedContext context, String servletName, String className, Servlet servlet) {
		super(servletName, className, context);
		this.servlet = servlet;
	}
	
	public Servlet getServlet() throws ServletException {
        if (!initialised) {
            synchronized (this) {
                if (!initialised) {
                    if (null == servlet) {
                        try {
                            servlet = (Servlet) Class.forName(getClassName()).newInstance();
                        } catch (Exception e) {
                            throw new ServletException(e);
                        }
                    }
                    servlet.init(this);
                    initialised = true;
                }
            }
        }
        return servlet;
    }

    @Override
    public void setLoadOnStartup(int loadOnStartup) {

    }

    @Override
    public Set<String> setServletSecurity(ServletSecurityElement constraint) {
        return null;
    }

    @Override
    public void setMultipartConfig(MultipartConfigElement multipartConfig) {

    }

    @Override
    public void setRunAsRole(String roleName) {

    }

    @Override
    public Set<String> addMapping(String... urlPatterns) {
        // TODO check for conflicts

        NettyEmbeddedContext context = getNettyContext();
        for (String urlPattern : urlPatterns) {
            context.addServletMapping(urlPattern, getName());
        }
        return Collections.emptySet();
    }

    @Override
    public Collection<String> getMappings() {
        return null;
    }

    @Override
    public String getRunAsRole() {
        return null;
    }

}
